//
//  RefreshMainView.swift
//  WeiBoDemo
//
//  Created by chaowen deng on 2021/3/31.
//

import SwiftUI
import BBSwiftUIKit

struct RefreshMainView: View {
    
    // 利用map方法，将range (0..<20)转变为数组
    @State var list: [Int] = (0..<20).map { $0 }
    
    @State var isRefreshing: Bool = false
    
    @State var isLoadingMore: Bool = false
    
    var body: some View {
        
        BBTableView(list) { i in
            Text("Text \(i)")
                .padding()
                .foregroundColor(.white)
                .background(Color.blue)
        }
        .bb_setupRefreshControl({ control in
            //自定义刷新样式
            control.tintColor = .blue
            control.attributedTitle = NSAttributedString(string: "正在加载...", attributes: [.foregroundColor: UIColor.blue])
        })
        .bb_pullDownToRefresh(isRefreshing: $isRefreshing) {
            print("下拉刷新")
            DispatchQueue.main.asyncAfter(deadline: .now()+1) {
                self.list = (0..<20).map { $0 }
                self.isRefreshing = false
            }
        }
        .bb_pullUpToLoadMore(bottomSpace: 30) {
            //底部间距大于30时，则会刷新，但有个问题，这里利用偏移量来计算，会多次执行加载更多的方法，所以需要加入bool变量来自己判断
            if self.isRefreshing { return }
            self.isRefreshing = true
            print("上拉刷新")
            // 数据获取完成
            DispatchQueue.main.asyncAfter(deadline: .now()+1) {
                let more = self.list.count..<self.list.count+10
                self.list.append(contentsOf: more)
                self.isRefreshing = false
            }
        }
    }
}

struct RefreshMainView_Previews: PreviewProvider {
    static var previews: some View {
        RefreshMainView()
    }
}
